<template>
  <div>
    <div
      class="relative"
      @mouseenter="onMouseenter"
      @mouseleave="onMounseleave"
    >
      <!-- 具名插槽,触发对象 -->
      <div ref="refErenceTarget">
        <slot name="reference"></slot>
      </div>
      <transition name="slide">
        <div
          :style="contentStyle"
          ref="refContentTarget"
          v-show="isVisable"
          class="absolute p-1 z-20 bg-white border rounded-md"
        >
          <slot></slot>
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup>
import { nextTick, ref, watch } from "vue-demi";
const props = defineProps({
  direction: {
    type: String,
    default: "left",
  },
});
const isVisable = ref(false);
let timeout;
const onMouseenter = () => {
  isVisable.value = true;
  if (timeout) {
    clearTimeout(timeout);
  }
};
const onMounseleave = () => {
  timeout = setTimeout(() => {
    isVisable.value = false;
  }, 100);
};
const contentStyle = ref({
  top: 0,
  left: 0,
});
// 触发对象的dom
const refErenceTarget = ref(null);
// 内容的
const refContentTarget = ref(null);
// 拿到指定元素的宽高
const useElementSize = (target) => {
  if (!target) return;
  console.log("object :>> ", target.offsetWidth);
  return {
    width: target.offsetWidth,
    height: target.offsetHeight,
    //  transform: 'translateY(40px)';
  };
};
watch(isVisable, (val) => {
  if (!val) return;
  nextTick(() => {
    // 计算出当前弹框的位置

    if (props.direction == "right") {
      contentStyle.value.transform = "translate(-50%,0)";
      contentStyle.value.top =
        useElementSize(refErenceTarget.value).height + 10 + "px";
      contentStyle.value.left = "50%";
    } else {
      contentStyle.value.top =
        useElementSize(refErenceTarget.value).height + "px";
      contentStyle.value.left =
        -useElementSize(refContentTarget.value).width + "px";
    }
  });
});
</script>

<style lang="scss" scoped>
.slide-enter-active,
.slide-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}
.slide-enter-from,
.slide-leave-to {
  opacity: 0;
  transform: translateY(40px);
}
</style>